package cn.pugle.oj.leetcode;

import cn.pugle.oj.catalog.Backtracking;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * https://leetcode.com/problems/subsets/  所有子集
 * <p>
 * 错误写法, 想用LinkedHashSet做一波优化, 结果偷鸡不成蚀把米
 * 因为这道题, [1, 2]和[2, 1]要求不重复, choice不是全部不在path里的, 选择choice的两行有问题咯
 *
 * @author tzp
 * @since 2020/10/16
 */
public class LC78 implements Backtracking {
    List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> subsets(int[] nums) {
        LinkedHashSet<Integer> path = new LinkedHashSet<>();
        for (int i = 0; i <= nums.length; i++) {
            backtracking(nums, i, path);
        }
        return result;
    }

    public void backtracking(int[] nums, int remainLength, LinkedHashSet<Integer> path) {
        if (remainLength == 0) {
            result.add(path.stream().map(x -> nums[x]).collect(Collectors.toList()));
        } else {
            for (int i = 0; i < nums.length; i++) {//这两行选择choice有问题咯
                if (!path.contains(i)) {
                    path.add(i);//mark used
                    backtracking(nums, remainLength - 1, path);
                    path.remove(i);//mark unused
                }
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(new LC78().subsets(new int[]{1, 2, 3}));
    }
}
